<template>
  <el-breadcrumb
    separator="/"
    class="mb-1"
    :class="{ 'mx-1': useLocale.isMob }"
    style="vertical-align: bottom"
  >
    <el-breadcrumb-item>
      <div class="flex align-center">
        <el-icon :size="18"> <User /> </el-icon><span class="pl">{{$t('menu.user')}}</span>
      </div>
    </el-breadcrumb-item>
    <el-breadcrumb-item>{{$t('menu.user-list')}}</el-breadcrumb-item>
  </el-breadcrumb>
  <div v-if="useLocale.isMob">
    <el-alert
      style="padding: 3px 5px"
      :title="content"
      type="warning"
      :closable="false"
    />
    <div class="mx-15 my-15 flex justify-between">
      <el-space :size="10">
        <el-button
          type="primary"
          size="small"
          plain
          round
          @click="batchUsersGroup"
          >{{$t('user.set-group')}}</el-button
        >
        <el-button
          type="primary"
          size="small"
          plain
          round
          @click="batchBindUsers"
          >{{$t('user.bind-user')}}</el-button
        >
        <el-button
          type="primary"
          size="small"
          plain
          round
          @click="batchDownload"
          >{{$t('common.download')}}</el-button
        >
      </el-space>
      <el-button
        :icon="Search"
        size="small"
        circle
        @click="
          () => {
            mobFilter = true;
          }
        "
      />
    </div>

    <div class="mob-list mt-2">
      <el-scrollbar ref="scrollbarRef" class="mob-scroll">
        <div
          class="mob-list-item text-content-color font"
          v-for="(item, index) in tableData"
        >
          <div class="flex align-center mb-1">
            <el-checkbox
              v-model="item.checked"
              @change="(value) => mobChecked(value, item)"
            />
            <el-avatar
              class="ml-1"
              shape="circle"
              :size="60"
              fit="fill"
              :src="item.user_img"
            />
            <div class="flex-1 ml-15">
              <div class="flex justify-between">
                <span class="font-mder text-main-color">{{
                  item.fb_name
                }}</span>
                <span>{{ item.user_type_name }}</span>
              </div>
              <div class="mt font-sm">{{ item.msg_user_id }}</div>
            </div>
          </div>
          <div class="flex justify-between border-bottom py-15">
            <span>{{$t('user.tab-consumption')}}</span>
            <div>
              <span>{{ item.e_consume_price }}</span
              >/<span :class="{ consume: Number(item.e_consume_num) > 0 }">{{
                item.e_consume_num
              }}</span>
            </div>
          </div>
          <div class="flex justify-between border-bottom py-15">
            <span>{{$t('user.tab-group')}}</span>
            <div>
              <span v-if="item.group_names == ''">-</span>
              <span v-else>{{ item.group_names }}</span>
            </div>
          </div>
          <div class="flex justify-between py-15">
            <span>{{$t('user.tab-isnew')}}</span>
            <span>{{ item.is_newuser }}</span>
          </div>
          <div wrap class="flex flex-wrap justify-end my-1">
            <el-button
              class="mb-1"
              size="small"
              plain
              round
              @click="openGroup(index, item)"
              >{{$t('user.set-group')}}</el-button
            >
            <el-button
              class="mb-1"
              v-if="item.group_names !== ''"
              size="small"
              plain
              round
              @click="quitGroup(index, item)"
              >{{$t('user.quit-group')}}</el-button
            >
            <el-button
              class="mb-1"
              v-if="item.user_type_id != 2"
              size="small"
              plain
              round
              @click="unbind(index, item)"
              >{{$t('user.unbind-user')}}</el-button
            >
            <el-button
              class="mb-1"
              size="small"
              plain
              round
              type="primary"
              @click="handleInfo(index, item)"
              >{{$t('user.userinfo')}}</el-button
            >
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div v-if="total > params.page_size" class="my-1 flex justify-center">
      <el-pagination
        v-model:current-page="params.current_page"
        v-model:page-size="params.page_size"
        :pager-count="5"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-card v-else class="box-card" shadow="hover">
    <el-alert :title="content" type="warning" :closable="false" />
    <div class="flex justify-between flex-wrap mb-2 mt">
      <el-space wrap :size="10" class="mt-1">
        <el-input
          v-model="params.fb_name"
          style="width: 150px"
          :placeholder="$t('user.username')"
        />
        <el-input
          v-model="params.msg_user_id"
          style="width: 150px"
          placeholder="PSID"
        />
        <el-input
          v-model="params.e_consume_price"
          style="width: 150px"
          type="number"
          min="0"
          :placeholder="$t('user.consume-price')"
        />
        <el-input
          v-model="params.e_consume_num"
          style="width: 150px"
          type="number"
          min="0"
          :placeholder="$t('user.consume-times')"
        />
        <el-select
          v-model="params.user_type_id"
          :placeholder="$t('user.tab-type')"
          style="width: 150px"
        >
          <el-option
            v-for="item in filter.usertype"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select-v2
          v-model="params.group_id"
          filterable
          :options="filter.group"
          :placeholder="$t('user.slect-group')"
          style="width: 150px"
          :props="{ value: 'id', label: 'name' }"
          clearable
        />
        <el-button :icon="Search" plain @click="search">{{$t('common.query')}}</el-button>
      </el-space>
      <el-space wrap :size="10" class="mt-1">
        <el-button type="primary" plain @click="batchUsersGroup"
          >{{$t('user.set-group')}}</el-button
        >
        <el-button type="primary" plain @click="batchBindUsers"
          >{{$t('user.bind-user')}}</el-button
        >
        <el-button type="primary" plain @click="batchDownload">{{$t('common.download')}}</el-button>
      </el-space>
    </div>
    <el-table
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column :label="$t('user.tab-photo')" align="center" width="150">
        <template #default="scope">
          <el-image
            style="width: 100px"
            :src="scope.row.user_img"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.tab-name')" align="center">
        <template #default="scope">
          <div class="flex flex-column align-center">
            <div>{{ scope.row.fb_name }}</div>
            <div class="mt">{{ scope.row.msg_user_id }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="user_type_name" :label="$t('user.tab-type')" />
      <el-table-column :label="$t('user.tab-consumption')">
        <template #default="scope">
          <span>{{ scope.row.e_consume_price }}</span
          >/<span :class="{ consume: Number(scope.row.e_consume_num) > 0 }">{{
            scope.row.e_consume_num
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.tab-group')">
        <template #default="scope">
          <span v-if="scope.row.group_names == ''">-</span>
          <span v-else>{{ scope.row.group_names }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_newuser" :label="$t('user.tab-isnew')" />
      <el-table-column fixed="right" :label="$t('common.operation')" width="150">
        <template #default="scope">
          <div class="ec2-btncon">
            <el-button
              link
              size="small"
              type="primary"
              @click="handleInfo(scope.$index, scope.row)"
              >{{$t('user.userinfo')}}</el-button
            >
            <el-button
              link
              size="small"
              type="danger"
              @click="openGroup(scope.$index, scope.row)"
              >{{$t('user.set-group')}}</el-button
            >
            <el-button
              v-if="scope.row.group_names !== ''"
              link
              size="small"
              type="info"
              @click="quitGroup(scope.$index, scope.row)"
              >{{$t('user.quit-group')}}</el-button
            >
            <el-button
              v-if="scope.row.user_type_id != 2"
              link
              size="small"
              type="warning"
              @click="unbind(scope.$index, scope.row)"
              >{{$t('user.unbind-user')}}</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="total > params.page_size" class="mt-2 flex justify-center">
      <el-pagination
        v-model:current-page="params.current_page"
        v-model:page-size="params.page_size"
        :page-sizes="[20, 40, 60]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <set-group
    ref="groupRef"
    :row="currRow"
    :type="groupType"
    :euids="currEuids"
    :muti="groupMuti"
  ></set-group>
  <el-drawer v-model="mobFilter" size="80%">
    <template #header>
      <h4>{{$t('common.filter')}}</h4>
    </template>
    <template #default>
      <el-space direction="vertical" fill style="width: 100%">
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">{{$t('user.username')}}</div>
          <el-input v-model="params.fb_name" />
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">PSID</div>
          <el-input v-model="params.msg_user_id" />
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">{{$t('user.consume-price')}}</div>
          <el-input v-model="params.e_consume_price" type="number" min="0" />
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">{{$t('user.consume-times')}}</div>
          <el-input v-model="params.e_consume_num" type="number" min="0" />
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">{{$t('user.tab-type')}}</div>
          <el-select
            v-model="params.user_type_id"
            style="width: 100%"
          >
            <el-option
              v-for="item in filter.usertype"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="mb-1">
          <div class="font-sm text-tips-color mb">{{$t('user.slect-group')}}</div>
          <el-select-v2
            v-model="params.group_id"
            filterable
            :options="filter.group"
            style="width: 100%"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </div>
      </el-space>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="mobClearFilter">{{$t('common.clear')}}</el-button>
        <el-button type="primary" @click="search">{{$t('common.query')}}</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { nextTick, ref, onMounted, reactive,watch ,computed} from "vue";
import { Search, User, ArrowDown } from "@element-plus/icons-vue";
import {
  $userlist,
  $usertype,
  $updateUserGroup,
  $unbindUser,
  $bindUser,
} from "@api/user";
import { $getGroup } from "@api/common";
import router from "@/router/";
import { useCommonStore } from "@/store/common";
import { useLocaleStore } from "@/store/locales";
import { transitionKey } from "@/assets/js/mybase";
import { useI18n } from "vue-i18n";
const {t}= useI18n();
const langkey = computed(() => useLocale.locale);
const useCommon = useCommonStore();
const useLocale = useLocaleStore();
const groupMuti = ref(false);
const groupType = ref("");
const groupRef = ref();
const scrollbarRef = ref();
const mobShowType = ref(false);
const mobTypeTxt = ref();
const mobFilter = ref(false);
let currEuids = ref([]);
let currRow = ref(null);
let params = ref({
  fb_name: "",
  msg_user_id: "",
  e_consume_num: "",
  e_consume_price: "",
  user_type_id: "",
  group_id: null,
  group_name: "",
  current_page: 1,
  page_size: 10,
});
const filter = ref({
  group: [],
  usertype: [],
  mobUserType: [],
});

const content = ref("");
const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getFilter();
});
const getFilter = async () => {
  const group_res = await $getGroup();
  const usertype_res = await $usertype();
  filter.value.group = group_res.data.list;
  filter.value.usertype = usertype_res.data.list;
  filter.value.mobUserType = transitionKey(usertype_res.data.list, {
    id: "value",
    name: "text",
  });
  console.log(filter.value.mobUserType);
  //初始化默认值
  params.value.user_type_id = usertype_res.data.list[0].id;
  mobTypeTxt.value = usertype_res.data.list[0].name;

  getData();
};

const getData = async () => {
  currEuids.value = [];
  let res = await $userlist(params.value);
  console.log(res);
  if (res.code == 0) {
    if (useLocale.isMob) {
      res.data.table.forEach((ele) => {
        Reflect.set(ele, "checked", false);
      });
    }
    tableData.value = res.data.table;
    total.value = res.data.total;
    content.value = `${t('user.alert1')}：${res.data.sum_private}，${t('user.alert2')}：${res.data.sum_activity} ，(${t('user.alert3')}：${res.data.sum_time})`;
    if (useLocale.isMob) {
      nextTick(() => {
        scrollbarRef.value.setScrollTop(0);
      });
    }
  }
};
const handleSizeChange = (val: number) => {
  params.value.page_size = val;
  getData();
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  params.value.current_page = val;
  getData();
};
const handleSelectionChange = (val) => {
  currEuids.value = [];
  if (val.length !== 0) {
    val.forEach((ele) => {
      currEuids.value.push(ele.euid);
    });
  }
};
const search = () => {
  console.log(params.value);
  getData();
  mobFilter.value = false;
};

const openGroup = (index, row) => {
  groupMuti.value = true;
  groupType.value = "user";
  currRow.value = row;
  currEuids.value = [];
  groupRef.value.changeShow();
};
const batchUsersGroup = () => {
  if (currEuids.value.length == 0) {
    ElMessage({
      message: t('user.select-user'),
      type: "warning",
    });
    return false;
  }
  groupMuti.value = false;
  groupType.value = "users";
  currRow.value = {};
  groupRef.value.changeShow();
};
const batchBindUsers = async () => {
  if (currEuids.value.length !== 2) {
    ElMessage({
      message: t('user.bindTips2'),
      type: "warning",
    });
    return false;
  }
  ElMessageBox.confirm(
    t('user.bindTips'),
    t('common.tips'),
    {
      confirmButtonText: t('common.confirmBtn'),
      cancelButtonText: t('common.cancelBtn'),
      type: "warning",
    }
  )
    .then(async () => {
      let res = await $bindUser({ euids: currEuids.value });
      if (res.code == 0) {
        ElMessage({
          message: t('common.success'),
          type: "success",
        });
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};
const batchDownload = () => {

   window.location.href = 'https://www.full2house.com'
};

const handleInfo = (index, row) => {
  console.log(row);
  router.push({
    path: "/user/info",
    query: {
      id: row.euid,
    },
  });
};
const quitGroup = (index, row) => {
  ElMessageBox.confirm(t('user.quitGroup'), t('common.tips'), {
    confirmButtonText: t('common.confirmBtn'),
    cancelButtonText: t('common.cancelBtn'),
    type: "warning",
    draggable: true,
  }).then(() => {
    quitUserGroup(row);
  });
};
const unbind = (index, row) => {
  ElMessageBox.confirm(t('user.unbindTips'), t('common.tips'), {
    confirmButtonText: t('common.confirmBtn'),
    cancelButtonText:t('common.cancelBtn'),
    type: "warning",
    draggable: true,
  }).then(() => {
    unbindUserGroup(row);
  });
};
const unbindUserGroup = async (row) => {
  let res = await $unbindUser({ euid: row.euid });
  if (res.code == 0) {
    ElMessage({
      message: t('common.success'),
      type: "success",
    });
    getData();
  } else {
    ElMessage.error(res.msg);
  }
};
const quitUserGroup = async (row) => {
  let res = await $updateUserGroup({ euid: row.euid });
  if (res.code == 0) {
    ElMessage({
      message: t('common.success'),
      type: "success",
    });
    getData();
  } else {
    ElMessage.error(res.msg);
  }
};
const refreshPage = () => {
  //location.reload();
  const currentRoute = router.currentRoute.value;
  console.log(currentRoute);
  router.replace(currentRoute);
  //router.replace({name: '404'});
};
const userTypeConfirm = ({ selectedValue, selectedOptions }) => {
  params.value.user_type_id = selectedValue[0];
  mobTypeTxt.value = selectedOptions[0].text;
  console.log(params);
};
const mobClearFilter = () => {
  params.value.fb_name = "";
  params.value.msg_user_id = "";
  params.value.e_consume_num = "";
  params.value.e_consume_price = "";
  params.value.user_type_id = filter.value.usertype[0].id;
  mobTypeTxt.value = filter.value.usertype[0].name;
  params.value.group_id = null;
  params.value.group_name = "";
  params.value.current_page = 1;
  params.value.page_size = 10;
  getData();
};
const mobChecked = (v, item) => {
  console.log(item);
  console.log(v);
  if (v == true) {
    currEuids.value.push(item.euid);
  } else {
    currEuids.value.splice(
      currEuids.value.findIndex((o) => o == item.euid),
      1
    );
  }
};

watch(langkey, (newVal, oldVal) => {
  console.log("新值:", newVal, "老值:", oldVal);
  getFilter();
});
</script>
<style>
.ec2-search {
  margin-right: 5px;
  .el-input__wrapper {
    border-radius: 30px;
  }
}
.ec2-btncon {
  .el-button {
    margin-bottom: 2px;
    justify-content: flex-start;
  }
  .el-button + .el-button {
    margin-left: 0;
  }
}
</style>
<style lang="scss" scoped>
.mob-scroll{
  height: calc(100vh - 320px);
}
.mob-list {
  .mob-list-item {
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
  }
  .desc-item {
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
  }
}
.consume {
  padding-left: 2px;
  color: var(--el-color-primary);
}
.ec2-btncon {
  display: flex;
  flex-direction: column;
}
</style>
